package iterables;

import interfaces.Expresion;

import java.util.Iterator;


public class AplanaIterableDeIterable<T1,T2> implements Iterable<T2> {
	private Iterable<T1> iterable1;
	private Expresion<? super T1,Iterable<T2>> e;
	
	public AplanaIterableDeIterable(Iterable<T1>i1, 
                 Expresion<? super T1,Iterable<T2>> e1) {
		iterable1 =i1;
		e=e1;
	}
	
	public Iterator<T2> iterator(){
		return new IteradorAplana();
	}
	
	private class IteradorAplana implements Iterator<T2> {
		private Iterator<T1> it1;
		private Iterator<T2> it2;
		//T1 a1;
		T2 a2;
		
		public IteradorAplana(){
			it1 = iterable1.iterator();
			if(it1.hasNext()){
				it2 = e.exp(it1.next()).iterator();
			}
			while(it1.hasNext()&&!it2.hasNext()){
				it2 = e.exp(it1.next()).iterator();
			}
		}
		
		public boolean hasNext(){
			return it1.hasNext() || it2.hasNext();
		}
		
		public T2 next() {
			while(it1.hasNext()&&!it2.hasNext()){
				it2 = e.exp(it1.next()).iterator();
			}
			if(it2.hasNext()){
				a2 = it2.next();
			}
			return a2;
	
		}
		public void remove() {}
	}
}

